﻿#region Header

// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------

#endregion

#region Usings

using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using ScrumTable.Common.Collections;

#endregion

namespace ScrumTable.Common.FileSystem
{
    /// <summary>
    /// Represents an utility class for path handling.
    /// </summary>
    public static class PathUtil
    {
        #region Declarations

        private const int MaxNtfsFileNameLength = 0xFF;
        private const char IllegalCharReplacement = '_';
        private const string MoreDataInFilePathPostFix = "...";

        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------
        
        #endregion

        #region Constructors / Destructor

        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        #endregion

        #region Methods

        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Converts the given file name into a valid file path name. This
        /// means that a file name which contains more than 255 characters
        /// will be truncated to 255 characters
        /// (including extension and post fix marker "...").
        /// </summary>
        /// <param name="fileName">Specifies the name of the file.</param>
        /// <param name="maxFileLength">Specifies the maximum length of the file.</param>
        /// <returns>Returns a valid file name with the</returns>
        public static string ToValidFileName(string fileName, int maxFileLength = MaxNtfsFileNameLength)
        {
            string validFileName = (fileName ?? string.Empty);

            foreach (char illegalChar in Path.GetInvalidFileNameChars())
            {
                validFileName = validFileName.Replace(illegalChar, IllegalCharReplacement);
            }

            if (validFileName.Length > maxFileLength)
            {
                string extension = (Path.GetExtension(validFileName) ?? string.Empty);
                int fileNameLength = maxFileLength - extension.Length - MoreDataInFilePathPostFix.Length;
                string fileNameReduced = validFileName.Substring(0, fileNameLength);

                validFileName = fileNameReduced + MoreDataInFilePathPostFix + extension;
            }
            return validFileName;
        }

        /// <summary>
        /// Returns the extension of the given file name without throwing an exception if
        /// a part of the path contains invalid path characters.
        /// </summary>
        /// <param name="fileName">Specifies the name of the file to get the extension from.</param>
        public static string GetExtensionSave(string fileName)
        {
            if (fileName != null)
            {
                int lastIndexOfDot = fileName.LastIndexOf('.');

                if (lastIndexOfDot != -1)
                {
                    string fileExtension = fileName.Substring(lastIndexOfDot, fileName.Length - lastIndexOfDot);

                    if (!ContainsInvalidFileChars(fileExtension))
                    {
                        return fileExtension;
                    }
                }
            }
            return string.Empty;
        }

        private static bool ContainsInvalidFileChars(string fileName)
        {
            IDictionary<char, char> invalidChars = Path.GetInvalidFileNameChars().Convert(c => new KeyValuePair<char, char>(c, c));

            for (int i = 0; i < fileName.Length; ++i)
            {
                if (invalidChars.ContainsKey(fileName[i]))
                {
                    return true;
                }
            }
            return false;
        }

        #endregion

        #region Events

        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        #endregion
    }
}